package com.yeshine.opendata.controller.front.front;

import com.yeshine.opendata.controller.front.AbstractFrontControllerBase;
import com.yeshine.opendata.entity.Data;
import com.yeshine.opendata.service.IDataService;
import com.yeshine.opendata.service.IDataThemeService;
import com.yeshine.opendata.service.IOrgService;
import com.yeshine.opendata.utils.PageResult;
import com.yeshine.opendata.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * Created by taohj on 2014/7/3.
 */
@Controller
@RequestMapping("/front/front/data/")
public class DataController extends AbstractFrontControllerBase {

    @Autowired
    IDataService service;




    @Autowired
    private IOrgService orgService;


    @Autowired
    private IDataThemeService themeService;





    @RequestMapping("view")
    public String detail(
            @RequestParam("id") Integer id
    ) {
        Data data = service.getById(id).getTarget();
        if (data == null) {
            return setMessage("访问失败", "该数据不存在");
        } else {
            setRequestAttr("data", data);
            return "/front/front/data/view";
        }
    }




    @RequestMapping("search")
    public String search(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
            @RequestParam(value = "org",required = false) Integer []  org,
            @RequestParam(value = "theme",required = false)  Integer [] theme,
            @RequestParam(value = "format",required = false) String [] format,
            @RequestParam(value = "key", required = false) String key
    ) {
        page = page != null ? page : 1;
        size = size != null ? size : 10;
        PageResult<Data> pageResult = new PageResult<Data>();
        pageResult.setPage(page);
        pageResult.setSize(size);
        pageResult.setKey(key);

        Data data=new Data();

        if(theme!=null && theme.length>0){
            data.setThemes(theme);
        }

        if (org!=null && org.length>0){
            data.setOrgIds(org);
        }

        if (format!=null && format.length>0){
            data.setFormats(format);
        }


        pageResult.setT(data);

        Result<Data> result = service.search(pageResult);

        setRequestAttr("result", result);
        setRequestAttr("key", key);
        System.out.println(key);


        setRequestAttr("orgs", orgService.getList(null));
        setRequestAttr("themes", themeService.getList(null));
        setRequestAttr("formats", service.getGroupByFormat(null));

        setRequestAttr("org",org);
        setRequestAttr("format",format);
        setRequestAttr("theme",theme);
        return "/front/front/data/search";
    }

}
